﻿using System;
using System.Net;
using System.Text;
using DHelpers.ExtensionsHelper;

namespace Core.NetWorkUtils
{
    public interface IWebHelper : IDisposable
    {
        string GetRequest(string ulr);
        string GetRequest(Uri ulr);

        void GetRequestAsync(string ulr);
        void GetRequestAsync(Uri ulr);

        byte[] GetData(string ulr);
        byte[] GetData(Uri ulr);
    }

    public class WebHelper : IWebHelper
    {
        public event EventHandler<EventArgs> OnDounloadComplite;

        public string Result { get; private set; }

        private readonly WebClient _client = new WebClient{ Encoding = Encoding.UTF8 };

        protected virtual void Complite(object sender, EventArgs e)
        {
            e.Raise(this, ref OnDounloadComplite);
        }

        #region Implementation

        public string GetRequest(string url)
        {
            return Get(new Uri(url));
        }

        public string GetRequest(Uri url)
        {
            return Get(url);
        }

        public void GetRequestAsync(string ulr)
        {
            GetAsync(new Uri(ulr));
        }

        public void GetRequestAsync(Uri ulr)
        {
            GetAsync(ulr);
        }

        public byte[] GetData(string ulr)
        {
            return GetDataByte(new Uri(ulr));
        }

        public byte[] GetData(Uri ulr)
        {
            return GetDataByte(ulr);
        }

        public void Dispose()
        {
            if (_client != null)
            {
                _client.DownloadStringCompleted -= ClientOnDownloadStringCompleted;
                _client.Dispose();
            }
        }

        #endregion

        private string Get(Uri url)
        {
            return _client.DownloadString(url);
        }

        private void GetAsync(Uri url)
        {
            _client.DownloadStringCompleted += ClientOnDownloadStringCompleted;
            _client.DownloadStringAsync(url);
        }

        private byte[] GetDataByte(Uri url)
        {
            return _client.DownloadData(url);
        }

        #region Events

        private void ClientOnDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            Result = e.Result;
        }

        #endregion
    }
}